<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <!-- load css -->
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/css/font/iconfont.css}" media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/layui/css/layui.css}"  media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap-table/bootstrap-table.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/table.css}"  media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/select2/css/select2.css}" media="all"/>

    <style>
        h2{
            margin: 0;
        }
        .blocks{
            display: flex;
            flex-direction: column;
            width: 20rem;
            height: 6rem;
        }
        .blockout{
            display: flex;
            justify-content: space-between;
            margin: 1.5rem 0;
            padding: 0 1rem;
        }
        #auditType{
            display: inline-block;
            min-width: 6rem;
            height: 3rem;
            background-color: #409EFF;
            border-radius: 4px;
            color: white;
            text-align: center;
            line-height: 3rem;
        }
        input[type="text"]:disabled{
            background-color: #EEF1F6;
        }
        input[type="text"]{
            height: 3rem;
        }
        #suppplierDetail{
            display: none;
        }
        #addInfor{
            width: 10rem;
            margin-left: 1rem;
            position: relative;
            top: 1rem;
            z-index: 1;
        }
        #tableForm{
            display: none;
        }
    </style>
</head>
<body>
<div class="layui-fluid larry-wrapper" id="StandardVUE">
    <div class="layui-row layui-col-space30">
        <div class="layui-col-xs24">
            <section class="panel panel-padding">
                <div class="layui-collapse" lay-filter="test">
                    <form id="form1" class="layui-form layui-form-pane" action="">
                        <div class="layui-colla-item">
                            <h2 class="layui-colla-title">供应商</h2>
                            <div class="layui-colla-content layui-show">
                                <div class="blocks" style="width: 25rem;">
                                    <label>供应商编号</label>
                                    <select type="text"
                                            lay-filter="supplierCode"
                                            name="supplierCode"
                                            id="supplierCode">
                                    </select>
                                </div>
                                <div id="suppplierDetail">
                                    <div class="blockout">
                                        <div class="blocks">
                                            <label>供应商名称</label>
                                            <span id="supName"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>联系人</label>
                                            <span id="supMan"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>电话1</label>
                                            <span id="supPhone1"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>电话2</label>
                                            <span id="supPhone2"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>传真</label>
                                            <span id="supFaxse"></span>
                                        </div>
                                    </div>
                                    <div class="blockout">
                                        <div class="blocks">
                                            <label>国家</label>
                                            <span id="supState"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>城市</label>
                                            <span id="supCity"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>省</label>
                                            <span id="supProvince"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>邮编</label>
                                            <span id="supPostCode"></span>
                                        </div>
                                        <div class="blocks">
                                            <label>详细地址</label>
                                            <span id="supAddress"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-colla-item">
                            <h2 class="layui-colla-title">采购订单信息</h2>
                            <div class="layui-colla-content layui-show">
                                <div class="blocks" style="margin-left: 1rem;">
                                    <label>PO编号</label>
                                    <div class="layui-input-inline">
                                        <input type="text"
                                               readonly
                                               class="layui-input"
                                               name="POcode"
                                               id="POcode"
                                               style="background-color: #EEF1F6;"/>
                                    </div>
                                    <span class="warning" id="POcodeWarning"></span>
                                </div>
                                <div class="blockout">
                                    <div class="blocks">
                                        <label>仓库名称</label>
                                        <div class="layui-input-inline">
                                            <!--<input type="text" class="layui-input" name="wareHouseName" id="wareHouseName" placeholder="仓库名称"/>-->
                                            <input th:value="${ckmc}"
                                                   name="wareHouseName"
                                                   id="wareHouseName"
                                                   autocomplete="off"
                                                   class="layui-input"
                                                   readonly
                                                   style="background-color: #EEF1F6;"/>
                                        </div>
                                    </div>
                                    <div class="blocks">
                                        <label>PO类型</label>
                                        <div class="layui-input-inline">
                                            <select type="text"
                                                    lay-filter="POtype"
                                                    lay-verify="required"
                                                    id="POtype"
                                                    name="POtype"
                                                    placeholder="PO类型">
                                            </select>
                                        </div>
                                    </div>
                                    <div class="blocks">
                                        <label>预计到货时间</label>
                                        <div class="layui-input-inline">
                                            <input type="text"
                                                   class="layui-input"
                                                   lay-verify="required"
                                                   id="planTime"
                                                   name="planTime"
                                                   placeholder="预计到货时间"/>
                                        </div>
                                    </div>
                                    <div class="blocks">
                                        <label>备注</label>
                                        <div class="layui-input-inline">
                                            <input type="text" class="layui-input" name="remark" id="remark" placeholder="备注"/>
                                        </div>
                                    </div>
                                    <div class="blocks">
                                        <label>审核状态</label>
                                        <div class="layui-input-inline">
                                            <span id="auditType"></span>
                                        </div>
                                        <span hidden id="zdsh" name="zdsh"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-colla-item">
                            <h2 class="layui-colla-title">采购订单明细</h2>
                            <div id="orderDetail" class="layui-colla-content layui-show" style="border-bottom: 2px solid #C5C5C5">
                                <div id="tableForm">
                                    <div class="blockout">
                                        <div class="blocks">
                                            <label>货品编号</label>
                                            <div class="layui-input-inline" id="goodsCodeS">
                                                <select class="form-control selectpicker bla bla bli "
                                                        style="width: 100%;"
                                                        lay-ignore="lay-ignore"
                                                        id="goodsCode"
                                                        name="goodsCode"
                                                        select2
                                                        placeholder="货品编号">
                                                </select>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>货品名称</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="goodsName" id="goodsName" placeholder="货品名称"/>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>包装名称</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="packName" id="packName" placeholder="包装名称"/>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>入库单位</label>
                                            <div class="layui-input-inline">
                                                <select class="form-control selectpicker bla bla bli "
                                                        lay-filter="warehouse"
                                                        id="warehouse"
                                                        name="warehouse"
                                                        placeholder="入库单位">
                                                </select>
                                                <span hidden id="warehouseSpan"></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="blockout">
                                        <div class="blocks">
                                            <label>体积</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="volume" id="volume" placeholder="体积"/>
                                                <span hidden id="volumeS"></span>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>净重</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="suttle" id="suttle" placeholder="净重"/>
                                                <span hidden id="suttleS"></span>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>毛重</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="grossWeight" id="grossWeight" placeholder="毛重"/>
                                                <span hidden id="grossWeightS"></span>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>金额</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled class="layui-input" name="money" id="money" placeholder="金额"/>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="blockout" style="width: 73%;">
                                        <div class="blocks">
                                            <label>主单位</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled="true" class="layui-input" name="unitNumber" id="unitNumber" placeholder="主单位"/>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>箱单位</label>
                                            <div class="layui-input-inline">
                                                <input type="text" disabled="true" class="layui-input" name="boxNumber" id="boxNumber" placeholder="箱单位"/>
                                            </div>
                                        </div>
                                        <div class="blocks">
                                            <label>总金额</label>
                                            <div class="layui-input-inline">
                                                <input type="text" class="layui-input" name="numMoney" id="numMoney" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="blockout">
                                        <div class="blocks" style="width: 69%">
                                            <label>备注</label>
                                            <div class="layui-input-inline">
                                                <input type="text" class="layui-input" name="datailRemark" id="datailRemark"/>
                                            </div>
                                        </div>
                                        <span hidden id="INDEXS"></span>
                                        <div class="blocks">
                                            <div class="layui-input-inline" style="margin-top: 2rem;">
                                                <a class="layui-btn" onclick="detailSave()">保存</a>
                                                <a class="layui-btn layui-btn-primary" onclick="tableFormReset()">取消</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <a class="layui-btn layui-btn-sm layui-btn-normal" id="addInfor" onclick="tableFormShow()">新增采购订单明细</a>
                                <section class="panel panel-padding layui-card-body" >
                                    <div class="pro">
                                        <table id="table" data-undefined-text=">_<" data-height="300" class="table text-nowrap"></table>
                                    </div>
                                </section>
                            </div>
                        </div>

                        <div class="layui-form-item" style="margin: 2rem 0;">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="add">立即提交</button>
                                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                            </div>
                        </div>
                    </form>
                </div>
            </section>
        </div>
    </div>
</div>
</body>
<div th:include="public/public_js::public_js"></div>
<script th:src="@{plugin/beyond/assets/js/fuelux/wizard/wizard-custom.js}"></script>

<script>

    var indexs = 0;
    var supplierInf;
    var POtypeData;

    $(function () {
        // 查询供应商编号
        $.ajax({
            url: '/zxsdwms/wmsPurchaseOrder/getWmsOwnerSupplierByHzid',
            type: 'GET',
            dataType: 'json',
            contentType: "application/json",
            async: false,
            data: '',
        }).then((resolve) => {
            supplierInf = resolve;
            var optionInf = optionRendering(resolve, 'id', 'mc');
            // 渲染供应商编号的<option>
            $('#supplierCode').append(optionInf);
        });


        // 查询Po类型的<option>
        $.ajax({
            url: '/zxsdwms/wmsPurchaseOrder/getPoLx',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({}),
            contentType: 'application/json',
            async: false,
        }).then((resolve) => {
            var optionInf = optionRendering(resolve, 'id', 'ddlx');
            POtypeData = resolve;
            // 渲染Po类型的<option>
            $('#POtype').append(optionInf);
        })


    })

    // option渲染方法
    function optionRendering(data, value, text) {
        var optionInf = '<option value="">请选择</option>';
        data.forEach(function (item) {
            optionInf += '<option value="'+ item[value] +'">'+ item[text] +'</option>';
        })
        return optionInf;
    }

    // 根据包装类型判断主单位是否禁用
    function packageType(type) {
        if (type == 0) {
            $('#unitNumber').attr("disabled",false);
            $('#boxNumber').attr("disabled",true);
        } else {
            $('#unitNumber').attr("disabled",true);
            $('#boxNumber').attr("disabled",false);
        }
    }

    //初始化PO类型的select2，select使用selec2时，Vue的@change方法不会被触发
    //    $('#POtype').select2({
    //        placeholder: '请选择PO类型',
    //        minimumResultsForSearch: -1
    //    });

    //    // 初始化货品编号的select2
    //    $('#goodsCode').select2({
    //        placeholder: '请选择货品'
    //    });

    // 初始化入库单位select2
    //    $('#warehouse').select2({
    //        placeholder: '请选择单位',
    //        minimumResultsForSearch: -1
    //    });


    // 查询入库单位
    function wareHouseUnit(id) {
        var DATA;
        $.ajax({
            url: '/zxsdwms/wmsPurchaseOrder/packDetailList/' + id,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            async: false,
            success: function (data) {
                DATA = data;
            }
        })
        return DATA;
    }

    function returnpage() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }

    function toFixeds (data) {
        var str = "";
        if (data) {
            data = data.toString();
            if (data.indexOf('.') < 0) {
                str = data;
            } else {
                str = data.substring(0, data.indexOf('.') + 3);
            }
            return parseFloat(str);
        } else {
            return data;
        }
    }

    layui.use(['myform','zzpUtils','form','laydate','jquery','zzpValidation'],function () {
        var form = layui.form,
            zzpUtils = layui.zzpUtils
            ,laydate = layui.laydate
            ,zzpValidation = layui.zzpValidation
            ,$ = layui.jquery;

        var UnitNum, UnitType, INDEXS = 0, INDEXS = 0, TYPE = 'add';

        //查询货品编号
        function goodsCode(ids) {
            var DATA;
            $.ajax({
                url: '/zxsdwms/wmsPurchaseOrder/getGoods',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                async: false,
            }).then(function (resolve) {
                DATA = resolve;
            })
            return DATA;
        }

        //  供应商编号的下拉选中触发
        form.on('select(supplierCode)', function (data) {
            if (data.value) {
                var supplierSelect = data.value;
                for (var i = 0; i < supplierInf.length; i++) {
                    var item = supplierInf[i];
                    if (item.id === supplierSelect) {
                        $('#supName').text(item.mc);
                        $('#supMan').text(item.lxr);
                        $('#supPhone1').text(item.dh1);
                        $('#supPhone2').text(item.dh2);
                        $('#supFaxse').text(item.cz);
                        $('#supState').text(item.gj);
                        $('#supCity').text(item.cs);
                        $('#supProvince').text(item.sheng);
                        $('#supPostCode').text(item.yb);
                        $('#supAddress').text(item.xxdz);
                        $('#suppplierDetail').css('display', 'block');
                        $.ajax({
                            url: '/zxsdwms/wmsPurchaseOrder/getBh/' + item.bh,
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json',
                            async: false,
                        }).then((resolve) => {
                            $('#POcode').val(resolve.bh);
                        })
                        break;
                    }
                }
                console.log('啦啦啦啦啦啦');
//                var gysid = {'gysid': data.value};
//                // 查询货品编号
//                var GoodsCode = goodsCode(gysid);
//                var optionInf = optionRendering(GoodsCode, 'goodsId', 'goodsBh');
//                // 给货品编号赋option
//                $('#goodsCode').find("option").remove();
//                $('#goodsCode').append(optionInf);
//                // 重新渲染form，否则新的option不显示
//                form.render();
                $('#goodsCode').select2({
                    ajax: {
                        url: '/zxsdwms/wmsPurchaseOrder/getGoods',
                        dataType: 'json',
                        type: 'POST',
                        contentType: "application/json",
                        data: function (params) {
                            var query = {
                                bh: params.term,
                                gysid: data.value
                            };
                            return JSON.stringify(query);
                        },
                        processResults: function (data) {
                            var arr= new Array();
                            console.log(arr);
                            if(data){
                                for (var i=0;i<data.length;i++){
                                    arr.push({
                                        id: data[i].goodsId,
                                        text: data[i].goodsBh});
                                }
                            }
                            console.log(arr);
                            // Tranforms the top-level key of the response object from 'items' to 'results'
                            return {
                                results: arr
                            };
                        },
                        cache: true
                    },
                    language: "zh-CN",
                    placeholder: '请输入查询字段',
                    allowClear: true
                })
            }
        })

        // PO类型的选中触发
        form.on('select(POtype)', function (data) {
            POtypeData.forEach(function (item) {
                if (item.id === data.value) {
                    $('#auditType').text(item.show_zdsh);
                    $('#zdsh').text(item.zdsh);
                }
            })
        })

        // 货品编号的选中触发
//        form.on('select(goodsCode)', function (data) {
//            if (data) {
//
//                var text = $("#goodsCode").find("option:selected").text();
//                var ids = {'bh': text, 'gysid': $('#supplierCode').val()};
//                var goodsCodeData = goodsCode(ids)[0];
//                $('#goodsName').val(goodsCodeData.goodsName);//包装名称
//                $('#packName').val(goodsCodeData.bzmc);//货品名称
//
//                var packId = goodsCodeData.packId;
//                var warehouseunit = wareHouseUnit(packId);
//                $('#warehouse').find("option").remove();
//                var options = '<option value="">请选择</option>';
//                warehouseunit.forEach(function (item) {
//                    options += "<option title='"+ JSON.stringify(item) +"' value='"+ item.ms +"'>"+ item.ms +"</option>";
//                });
//                $('#warehouse').append(options);
//                form.render();
//            }
//        })

        // 货品编号的选中触发
        $("#goodsCode").on("select2:select",function(e){
            var data = e.params.data;
            if (data) {
//                var text = $("#goodsCode").find("option:selected").text();
                var ids = {'bh': data.text, 'gysid': $('#supplierCode').val()};
                var goodsCodeData = goodsCode(ids)[0];
                $('#goodsName').val(goodsCodeData.goodsName);//包装名称
                $('#packName').val(goodsCodeData.bzmc);//货品名称

                var packId = goodsCodeData.packId;
                warehousefun(packId);
            }
        })

        function warehousefun(packId) {
            var warehouseunit = wareHouseUnit(packId);
            $('#warehouse').find("option").remove();
            var options = '<option value="">请选择</option>';
            warehouseunit.forEach(function (item) {
                options += "<option title='"+ JSON.stringify(item) +"' value='"+ item.ms +"'>"+ item.ms +"</option>";
            });
            $('#warehouse').append(options);
            form.render();
        }

        // 入库单位选中触发
        form.on('select(warehouse)', function (data) {
            var datas = $('#warehouse').find("option:selected");
            var wareHouseData = JSON.parse(datas[0].title);
            $('#volume').val(wareHouseData.tj);
            $('#volumeS').text(wareHouseData.tj);

            $('#suttle').val(wareHouseData.jz);
            $('#suttleS').text(wareHouseData.jz);

            $('#grossWeight').val(wareHouseData.zl);
            $('#grossWeightS').text(wareHouseData.zl);

            $('#money').val(wareHouseData.je);
            $('#numMoney').val(0);
            $('#unitNumber').val(0);
            $('#boxNumber').val('0箱0件');

            $('#warehouseSpan').text(wareHouseData.id);

            packageType(wareHouseData.bzlx);
            // 主单位数量
            UnitNum = wareHouseData.zdwsl;
            UnitType = wareHouseData.bzlx;

        })

        // 监听主单位数量
        $('#unitNumber').on('input propertychange', function(data) {
            var value =  data.currentTarget.value;
            var len, lenfloat;
            var volumeS = parseFloat($('#volumeS').text());
            var suttleS = parseFloat($('#suttleS').text());
            var grossWeightS = parseFloat($('#grossWeightS').text());
            var money = parseFloat($('#money').val());
            // 如果value不为空
            if (value && value !== '0') {
                len = parseInt(value);
                lenfloat = parseFloat(value);
                if (value.indexOf('-') >= 0) {
                    $('#unitNumber').val('');
                } else if ((lenfloat - len) > 0) {
                    $('#unitNumber').val(len);
                } else {
                    $('#volume').val(toFixeds(volumeS * len));
                    $('#suttle').val(toFixeds(suttleS * len));
                    $('#grossWeight').val(toFixeds(grossWeightS * len));
                    $('#numMoney').val(toFixeds(money * len));

                    // 如果主单位数量为1
                    if (UnitNum === 1) {
                        $('#boxNumber').val(len.toString() + '箱0件');
                    } else {
                        var BOX,PIECE;
                        BOX = parseInt(len/UnitNum);
                        PIECE = len%UnitNum;
                        $('#boxNumber').val(BOX + '箱'+ PIECE +'件');
                    }

                }

            } else {
                $('#volume').val(volumeS);
                $('#suttle').val(suttleS);
                $('#grossWeight').val(grossWeightS);
                $('#numMoney').val(0);
                $('#boxNumber').val('0箱0件');
            }

        })

        // 监听箱单位数量
        $('#boxNumber').on('input propertychange', function(data) {
            var value, indbox, indpiece, box, piece, boxs, pieces;
            var volumeS = parseFloat($('#volumeS').text());
            var suttleS = parseFloat($('#suttleS').text());
            var grossWeightS = parseFloat($('#grossWeightS').text());
            var money = parseFloat($('#money').val());
            value =  data.currentTarget.value;
            indbox = value.indexOf('箱');
            indpiece = value.indexOf('件');
            box = value.substring(0, indbox);
            piece = value.substring(indbox + 1,  indpiece);
            boxs = parseFloat(box) - parseInt(box);
            pieces = parseFloat(piece) - parseInt(piece);
            if (boxs > 0 && pieces > 0) {
                $('#unitNumber').val(box + '箱'+ piece +'件');
            }
            if (boxs < 0 && pieces > 0) {
                $('#unitNumber').val(Math.abs(box) + '箱'+ piece +'件');
            }
            if (boxs > 0 && pieces < 0) {
                $('#unitNumber').val(box + '箱'+ Math.abs(piece) +'件');
            }
            if (parseInt(box) >= 0 && parseInt(piece) >= 0) {
                var unitNumber = parseInt(box) * UnitNum + parseInt(piece);
                var len;
                if (unitNumber !== 0) {
                    len = unitNumber;
                    $('#numMoney').val(toFixeds(money * len));
                } else {
                    len = 1;
                    $('#numMoney').val(0);
                }
                $('#unitNumber').val(unitNumber);
                $('#volume').val(toFixeds(volumeS * len));
                $('#suttle').val(toFixeds(suttleS * len));
                $('#grossWeight').val(toFixeds(grossWeightS * len));

            }
        })

        // 预计到货时间的时间初始化
        laydate.render({
            elem: '#planTime'
            ,type: 'datetime'
        });

        // 行内按钮
        window.operateEvent ={
            // 触发table行内回显
            "click #editRow":function (e, value, row, index) {
                console.log('rrrrrrrr', row);
                TYPE = 'edit';
                $('#tableForm').css('display','block');
                $('#addInfor').css('display','none');

                var ids = {'bh': row.bh, 'gysid': $('#supplierCode').val()};
                var packId = goodsCode(ids)[0].packId;
                warehousefun(packId);

                $('#goodsCode').val(row.hpid);
                $('#goodsName').val(row.mc);
                $('#packName').val(row.bzmc);
                $('#warehouse').val(row.ms);
                $('#volume').val(row.tj);
                $('#volumeS').text(row.tjS);
                $('#suttle').val(row.jz);
                $('#suttleS').text(row.jzS);
                $('#grossWeight').val(row.zl);
                $('#grossWeightS').text(row.zlS);
                $('#money').val(row.price);
                $('#numMoney').val(row.je);
                $('#unitNumber').val(row.sl);
                $('#boxNumber').val(row.xdwsl);
                $('#remark').val(row.bz);
                $('#INDEXS').text(row.index);
                form.render('select');
            },
            "click #delete":function (e, value, row, index) {
                console.log('触发了删除', row);
                var id = [];
                id.push(row.hpid);
                // 使用remove方法时values必须是一个数组
                blanktable.bootstrapTable('remove', {field: 'hpid', values: id});

                var tableData = blanktable.bootstrapTable('getData');
                // 加载数据到表格中，旧数据会被替换,相当于刷新table
                blanktable.bootstrapTable('load', tableData);
            },
        }

        function operateFormatter(value, row, index) {
            return [
                '<a class="layui-btn layui-btn-xs" id="editRow">编辑</a>',
                '<a class="layui-btn layui-btn-danger layui-btn-xs" id="delete">删除</a>'
            ].join('')
        }

        // 初始化一个空table
        var blanktable = zzpUtils.table({
            elem: '#table',
            isApi: true,
            pagination: false,//分页开关
            checkboxHeader: false,
            showColumns: false,// 列选择
            columns: [
                {field:'bh',title:'货品编号'},
                {field:'mc',title:'货品名称'},
                {field:'bzmc',title:'包装名称'},
//                {field:'hgl',title:'合格率'},
                {field:'sl',title:'主单位数量'},
                {field:'ms',title:'主单位'},
                {field:'xdwsl',title:'箱单位数量'},
                {field:'je',title:'总金额'},
                {field:'bz',title:'备注'},
                {field:'tj',title:'体积'},
                {field:'jz',title:'净重'},
                {field:'zl',title:'毛重'},
                {field:'price',title:'单价'},
                {
                    field:'caozuo',
                    title: '操作',
                    width: 200,
                    events:operateEvent,
                    formatter:operateFormatter
                }],
        });

        // 在外部可以调用layer内部的方法
        // 向table添加数据
        window.detailSave = function() {
            var data = {};
            console.log('保存触发测试');
            data.hpid = $("#goodsCode").val();
            data.bh = $("#goodsCode").find("option:selected").text();// 货品编号
            data.mc = $('#goodsName').val();// 货品名称
            data.bzmc = $('#packName').val(); // 包装名称
            data.ms = $('#warehouse').val();// 入库单位
            data.tj = $('#volume').val();// 体积
            data.tjS = $('#volumeS').text();
            data.jz = $('#suttle').val();// 净重
            data.jzS = $('#suttleS').text();
            data.zl = $('#grossWeight').val();// 毛重
            data.zlS = $('#grossWeightS').text();
            data.price = $('#money').val();// 单价
            data.je = $('#numMoney').val();// 总金额
            data.bz = $('#remark').val();// 备注
            data.sl = $('#unitNumber').val();// 主单位数量
            let xdwsl = $('#boxNumber').val();// 箱单位数量
            console.log('xdwsl', xdwsl, UnitNum);
            data.xdwsl = xdwslReset(xdwsl);
            data.zdw = $('#warehouseSpan').text();
            data.zdwsl = UnitNum;
            data.index = $('#INDEXS').text();

            if (data.ms !== '') {
                if(data.sl !== '') {
                    var blanktableData = blanktable.bootstrapTable('getData');
                    if (blanktableData.length === 0) {
                        data.index = 0;
                        blanktable.bootstrapTable('append', data);
                        $('#tableForm').css('display','none');
                        $('#addInfor').css('display','block');
                    } else {
                        var type = blanktableData.every(function (item) {
                            console.log(item.index, data.index)
                            return item.index != data.index;
                        });
                        if (TYPE === 'add') {
                            console.log('执行添加');
                            indexs += 1;
                            data.index = indexs;
                            blanktable.bootstrapTable('append', data);
                            $('#tableForm').css('display','none');
                            $('#addInfor').css('display','block');
                        } else {
                            console.log('执行更新');
                            var In = parseInt($('#INDEXS').text());
                            blanktable.bootstrapTable('updateRow', {index: In, row: data});
                            $('#tableForm').css('display','none');
                            $('#addInfor').css('display','block');
                        }
                    }
                } else {
                    layer.msg('您必选填写主单位或箱单位');
                }
            } else {
                layer.msg('您必选选择货品和入库单位');
            }

            $('#orderDetail input[type="text"]').val('');
//            $('#goodsCode').val("").select2();
        }
        
        function xdwslReset(data) {
            var indbox = data.indexOf('箱');
            var indpiece = data.indexOf('件');
            var box = data.substring(0, indbox);
            var piece = data.substring(indbox + 1,  indpiece);
            var sumnumbers = (parseInt(box) * parseInt(UnitNum)) + parseInt(piece);
            var BOX,PIECE;
            BOX = parseInt(sumnumbers/UnitNum);
            PIECE = sumnumbers%UnitNum;
            return BOX + '箱' + PIECE + '件';
        }

        window.tableFormShow = function (data) {
            console.log('新增触发')
            TYPE = 'add';
            $('#tableForm').css('display','block');
            $('#addInfor').css('display','none');
        };

        window.tableFormReset = function(){
            $('#tableForm').css('display','none');
            $('#addInfor').css('display','block');
            $('#tableForm input').val('');
        }

        form.on("submit(add)",function(data){
            var field = data.field;
            zzpUtils.confirm("是否确定添加",function(index){
                //获取table数据
                var TableData = blanktable.bootstrapTable('getData');
                var SaveData = {};
                if (TableData.length > 0) {
                    var newTableData = [];
                    TableData.forEach(function (item) {
                        var items = item;
                        delete items.index;
                        delete item.jzS;
                        delete item.tjS;
                        delete item.zlS;
                        newTableData.push(items);
                    });

                    SaveData.gysid = field.supplierCode;// 供应商id
                    SaveData.bh = field.POcode;// PO编号
                    SaveData.lx = field.POtype;// PO类型
                    var time = field.planTime;
                    time = new Date(time);
                    SaveData.yjdhsj = time.getTime();// 预计到货时间
                    SaveData.bz = field.remark;// 备注
                    SaveData.zdsh = field.zdsh;
                    SaveData.wpodList = newTableData;

                    $.ajax({
                        url: '/zxsdwms/wmsPurchaseOrder/add',
                        type: 'POST',
                        dataType: 'json',
                        contentType: 'application/json',
                        data: JSON.stringify(SaveData),
                        success: function (data) {
                            layer.msg(data.title);
                            if (data.type === 'success') {
                                setTimeout(function(){
                                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                    parent.layer.close(index); //再执行关闭
                                    top.layer.msg(data.message);
                                },500);
                            }
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    })
                } else {
                    layer.msg('您还不能保存，采购订单明细为必填项');
                }
            })
            return false;
        })

    });

</script>
</html>